/*!
 * \file StreamReader.cpp
 * \date 12-7-2012 16:04:10
 * 
 * 
 * \author zjhlogo (zjhlogo@gmail.com)
 */
#include "../Inc/StreamReader.h"
#include <memory>

StreamReader::StreamReader(const void* pBuffer, int nBufferSize, bool bManageBuffer /* = false */)
{
	m_pBuffer = (const char*)pBuffer;
	m_nBufferSize = nBufferSize;
	m_bManageBuffer = bManageBuffer;
	m_nReadPos = 0;
}

StreamReader::~StreamReader()
{
	if (m_bManageBuffer && m_pBuffer)
	{
		delete[] m_pBuffer;
		m_pBuffer = NULL;
	}
}

bool StreamReader::read(void* pDataOut, int nSize)
{
	if (!pDataOut || nSize + m_nReadPos > m_nBufferSize) return false;
	if (nSize <= 0) return true;

	const void* pBuffer = getBuffer();
	memcpy_s(pDataOut,nSize, pBuffer, nSize);
	m_nReadPos += nSize;

	return true;
}

bool StreamReader::skip(int nSize)
{
	if (nSize + m_nReadPos > m_nBufferSize) return false;
	m_nReadPos += nSize;
	return true;
}

void StreamReader::reset()
{
	m_nReadPos = 0;
}

const void* StreamReader::getBuffer()
{
	const char* pBuffer = m_pBuffer;
	pBuffer += m_nReadPos;
	return pBuffer;
}

int StreamReader::getSize()
{
	return m_nBufferSize - m_nReadPos;
}

int StreamReader::getPosition()
{
	return m_nReadPos;
}
